//
//  YH_AddMoreFileViewController.m
//  YinHang
//
//  Created by apple on 14-9-24.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_AddMoreFileViewController.h"
#import "EncodeToMP4.h"//视频压缩

@interface YH_AddMoreFileViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,SendResultUrl,ASIHTTPRequestDelegate>{

    __weak IBOutlet UIView *topView;
    __weak IBOutlet UILabel *barView;
    __weak IBOutlet UITextField *fileName;

    __weak IBOutlet UIImageView *ImageView;
    __weak IBOutlet UIButton *fileButton;

    __weak IBOutlet UIImageView *fileImage;

    __weak IBOutlet UITextView *fileDetails;
    
    __weak IBOutlet UIButton *filePresentButton;
    
    UIImagePickerController *imgPC;//UIImagePickerController对象
    
    EncodeToMP4 *encodeToMP4;//视频压缩帮助类
    
    UIImage *image;//最终的图片
    UIImage *thumbnail;//视频第一帧
    
    NSString *imgFileByte;//图片上传filebyte参数
    NSString *videoFileByte;//视频上传filebyte参数
    MBProgressHUD *postHud;
    BOOL isVideo;
    ASIFormDataRequest *postUploadFile;//发送请求
    ASIFormDataRequest *postUpload;//发送请求
    
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    NSString *filename;
    
    NSString *content;//返回图片地址后和内容拼成的字符串
    NSString *imgFilePath;//图片或视频缩略图地址
    NSString *videoFilePath;//视频地址
    NSString *filePath;//内容图片地址
    NSString *path;
}

@end

@implementation YH_AddMoreFileViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUI];
    // Do any additional setup after loading the view from its nib.
    //设置模拟navbar的颜色
    topView.backgroundColor= barView.backgroundColor=APP_COLOR;
    if (MAIN_VERSION < 7) {
        topView.frame = CGRectMake(0, 0, 0, 0);
    }
   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)setUI{
    self.navigationItem.title = @"添加上传文件";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
}
-(void)back{
    [postUploadFile cancel];
    [postUpload cancel];
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)fileButtonClick:(id)sender {
    
    
}
- (IBAction)filePresentButtonClick:(id)sender {
    
//    [self dismissViewControllerAnimated:YES completion:^{
//        
//        [_delegate didSaveData:fileName.text];
//        
//    }];
    if (fileName.text.length == 0 || fileDetails.text.length == 0 || ImageView.image == [UIImage imageNamed:@"placeholder.png"] ) {
        return;
    }
    [self postRequest];
    
    
}
//选择文件
- (IBAction)ChoicePhoto:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        imgPC = [[UIImagePickerController alloc]init];
        imgPC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 媒体类型——相册
        imgPC.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//        if (selectedIndex_ != 2) {//不是视频
//            // 设置媒体类型(NSArray)（指定是选择静态的图片还是录像）
//            imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
//        } else {// 视频
//            imgPC.mediaTypes = @[(NSString*)kUTTypeMovie];
//        }
        imgPC.allowsEditing = YES;
        imgPC.delegate = self;
        
        [self presentViewController:imgPC animated:YES completion:nil];
    }
}
//拍照上传
- (IBAction)TakePhoto:(id)sender {
    // 检查设备是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        // 创建UIImagePickerController对象
        imgPC = [[UIImagePickerController alloc]init];
        // 设置源类型（确定是调用摄像头还是调用图片库）
        imgPC.sourceType = UIImagePickerControllerSourceTypeCamera;
//        if (selectedIndex_ != 2) {//不是视频
//            // 设置媒体类型(NSArray)（指定是拍静态的图片还是录像）
//            imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
//        } else {// 视频
//            imgPC.mediaTypes = @[(NSString*)kUTTypeMovie];
//        }
        
        // 设置允许编辑
        imgPC.mediaTypes = @[(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie];
        imgPC.allowsEditing = YES;
        // 设置代理对象
        imgPC.delegate = self;
        
        // 弹出模式视图控制器
        [self presentViewController:imgPC animated:YES completion:nil];
    }

}

- (IBAction)imgageUpload:(id)sender {
    
}

#pragma mark - UIImagePickerControllerDelegate

// 拍摄完成后要执行的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        
        // 处理照片
        if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
            isVideo = NO;
            UIImage *origImg;//原始图片
            UIImage *editedImg;//编辑后的图片
            
            
            // 获取原始图片
            origImg = [info objectForKey:UIImagePickerControllerOriginalImage];
            // 获取编辑后的图片
            editedImg = [info objectForKey:UIImagePickerControllerEditedImage];
            
            if (editedImg) {
                image = editedImg;
            }else{
                image = origImg;
            }
            
            if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
                // 保存到相机胶卷（相册图库）
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
            }
            
            ImageView.image = image;
            
            
            // 视频缩略图data
            NSData *imageData = UIImagePNGRepresentation(image);
            imgFileByte = [imageData hexadecimalString];
            //NSLog(@"%@",imgFileByte);
            
            isVideo = NO;
            
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        // 处理录像
        if ([mediaType isEqualToString:(NSString*)kUTTypeMovie]) {
            // 视频路径
            isVideo = YES;
            NSURL *videoUrl_Origin = [info objectForKey:UIImagePickerControllerMediaURL];
            NSString *videoPath = (NSString*)[videoUrl_Origin path];
            //NSLog(@"%@",videoPath);
            
            if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
                
                if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath)) {
                    
                    UISaveVideoAtPathToSavedPhotosAlbum(videoPath, nil, nil, nil)
                    ;
                }
            }
            
            //NSLog(@"%@",videoUrl_Origin);
            
            // 显示视频缩略图
            MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoUrl_Origin];
            moviePlayer.shouldAutoplay = NO;
            thumbnail = [moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
            
            ImageView.image = thumbnail;
            // 图片data
            NSData *imageData = UIImagePNGRepresentation(thumbnail);
            imgFileByte = [imageData hexadecimalString];
            //NSLog(@"%@",imgFileByte);
            
            //isVideo = NO;
            
            // 初始化视频压缩帮助类
            encodeToMP4 = [[EncodeToMP4 alloc]init];
            encodeToMP4.delegate = self;
            // 开始压缩
            [encodeToMP4 start:videoUrl_Origin hasVideo:YES isSave:NO];
            
            
            [self dismissViewControllerAnimated:YES completion:^{
                //                // 播放视频
                //                MPMoviePlayerViewController *pvc = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]];
                //                [self presentMoviePlayerViewControllerAnimated:pvc];
                //                [pvc.moviePlayer play];
            }];
        }
}

#pragma mark - SendResultUrl
// 压缩完成后传回来的视频地址
- (void)backResultDatainfo:(NSURL *)url {
    //NSLog(@"%@",url);
    NSData *videoData = [NSData dataWithContentsOfURL:url];
    
    videoFileByte = [videoData hexadecimalString];
    //NSLog(@"%@",videoFileByte);
    
    isVideo = YES;
}

// 点击cancel后执行的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 获取当前时间
- (NSString*)getCurrentDateTime {
    NSDate *senddate=[NSDate date];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMddhhmmss"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    //NSLog(@"locationString:%@",locationString);
    
    return locationString;
}

-(void)postUpLoad{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (postUpload) {
                postHud.hidden = NO;
                return;
            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postUpload = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postUpload.requestMethod = @"POST";
        // 设置超时时间
        postUpload.timeOutSeconds = 60;
        postUpload.delegate = self;
        // 设置参数
        NSString *title = fileName.text;
        NSString *contentStr = fileDetails.text;
        NSString *actionStr = @"uploadadd";
        paramsDict = @{@"uid":UNAME,@"title":title,@"url":path,@"picture":@"",@"content":contentStr};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postUpload.postBody = [paramsData mutableCopy];
        
        [postUpload startAsynchronous];
    }

}
-(void)postRequest{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (postUpload) {
                postHud.hidden = NO;
                return;
            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postUploadFile = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postUploadFile.requestMethod = @"POST";
        // 设置超时时间
        postUploadFile.timeOutSeconds = 60;
        postUploadFile.delegate = self;
        // 设置参数
        filename = [self getCurrentDateTime];
        NSString *actionStr = @"";
        if (!isVideo) {
            actionStr = @"fileupload1";
            filename = [NSString stringWithFormat:@"%@.png",filename];
            paramsDict = @{@"uid":UNAME,@"cid":UID,@"filename":filename,@"filebyte":imgFileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        } else {
            actionStr = @"fileuploadvideo";
            filename = [NSString stringWithFormat:@"%@.flv",filename];
            paramsDict = @{@"uid":UNAME,@"cid":UID,@"filename":filename,@"filebyte":videoFileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postUploadFile.postBody = [paramsData mutableCopy];
        
        [postUploadFile startAsynchronous];
    }

}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    if (request == postUploadFile) {
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                
                // 文件（图片、视频）上传成功
                NSDictionary *info = result[@"info"];
                if (!isVideo) {
                    imgFilePath = info[@"filepath"];//图片地址
                    //imgFilePath = [NSString stringWithFormat:@"%@%@",URL_DOMAIN,info[@"filepath"]];//图片地址
//                    if (selectedIndex_ == 2) {
//                        isVideo = YES;
//                    }
                    path = imgFilePath;
                } else {
                    videoFilePath = info[@"filepath"];//视频地址
                    path = videoFilePath;
                    isVideo = NO;
                }
                [self postUpLoad];//发送提交请求
                
            } else {
                [postHud hide:YES];
                postHud = Nil;
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            postHud = Nil;
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }else{
            NSError *err;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
            
            // 1. 是否解析有错误
            if (!err) {
                
                // 2. 判断错误码
                NSInteger errorCode = [result[@"errorCode"]integerValue];
                if (errorCode == 0) {
                    [postHud hide:YES];
                    postHud = Nil;
                   // NSDictionary *info = result[@"info"];
                    //NSString *newsId = info[@"id"];
                    
                    [SVProgressHUD showSuccessWithStatus:@"发布成功！"];
                    // 提示发布成功
                    double delayInSeconds = 2.0;
                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                } else {
                    [postHud hide:YES];
                    postHud = Nil;
                    [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
                }
            } else {
                [postHud hide:YES];
                postHud = Nil;
                [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
            }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [postHud hide:YES];
    //BOOL b = postHud.hidden;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)dealloc{
    [postUploadFile cancel];
    postHud = nil;
    [postUpload cancel];
}
@end
